//
//  EFAddCartView.m
//  EnjogFood
//
//  Created by guocheng on 2017/5/25.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFAddCartView.h"
#import "EFGoodCountViewItem.h"
#import "EFGoodCountViewCell.h"
#import "EFGoodScaleViewItem.h"
#import "EFGoodScaleViewCell.h"
#import "EFGoodsModelItem.h"
#import "EFSepecialItem.h"
#include "iToast.h"


@interface EFAddCartView()<UITableViewDelegate, UITableViewDataSource>

@property(strong,nonatomic)UIView* bgView;
@property(strong,nonatomic)UIView* transparentBgView;
@property(strong,nonatomic)UIView* bodyView;

@property(strong,nonatomic)UIView* goodsView;
@property(strong,nonatomic)UIImageView* goodsIV;
@property(strong,nonatomic)UILabel* priceLabel;
@property(strong,nonatomic)UILabel* salePriceLabel;
@property(strong,nonatomic)UIButton* closeBtn;
@property(strong,nonatomic)UIView* lineView;


@property(strong,nonatomic)UITableView* tableView;
@property(strong,nonatomic)NSMutableArray* dataArray;

@property(strong,nonatomic)UIButton* okBtn;
@property(strong,nonatomic)NSString* productId;

@property(strong,nonatomic)NSString* price;
@property(strong,nonatomic)NSString* salePrice;



@end


@implementation EFAddCartView


- (instancetype)init
{
    self = [super init];
    if (self) {
        self.dataArray = [NSMutableArray array];
        [self initView];
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame productId:(NSString*)productId img:(NSString *)img price:(NSString *)price salePrice:(NSString *)salePrice count:(NSInteger)count scaleView:(EFGoodScaleViewItem*)scaleView{
    self = [super initWithFrame:frame];
    if (self) {
        self.productId = productId;
        self.userInteractionEnabled = YES;
        self.dataArray = [NSMutableArray array];
        [self initView];
        
        [self.goodsIV setImageWithURL:[NSURL URLWithString:img]];
        
        [self.priceLabel setText:[NSString stringWithFormat:@"¥%@",salePrice]];
        [self.priceLabel sizeToFit];
        
        self.price = salePrice;
        self.salePrice = price;
        
        //中划线
        NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};;
        NSString* strSalePrice = [NSString stringWithFormat:@"¥%@",price];
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:strSalePrice attributes:attribtDic];
        self.salePriceLabel.attributedText = attribtStr;
        [self.salePriceLabel sizeToFit];
        
        self.goodsView.left = 20;
        self.goodsView.top = -20;
        
        self.priceLabel.left = self.goodsView.right + 11;
        self.priceLabel.top = 35;
        
        self.salePriceLabel.left = self.goodsView.right + 11;
        self.salePriceLabel.top = self.priceLabel.bottom + 8;
        
        self.lineView.top  = self.goodsView.bottom + 12;
        self.lineView.left  = 20;
        
        self.closeBtn.left = kScreenWidth - self.closeBtn.width - 20;
        self.closeBtn.top = 10;
        
        
        self.tableView.height = 45 ;
        if(scaleView != nil  && scaleView.model.count >0 ){
            self.tableView.height = 45 + 45;  //多一行规格参数选择
            [self.dataArray addObject:scaleView];
        }
        self.tableView.top = self.lineView.bottom;
        
        self.bodyView.width = kScreenWidth;
        self.bodyView.height = self.tableView.height + self.okBtn.height + 144;
        self.bodyView.top = kScreenHeight - self.bodyView.height ;
        
        self.okBtn.top = self.bodyView.height -  50;
        
        
        EFGoodCountViewItem* countItem = [[EFGoodCountViewItem alloc]init];
        countItem.count = count;
        [self.dataArray addObject:countItem];
        
        [self.tableView reloadData];
    }
    
    return self;
}

-(void)initView{
    [self.goodsView addSubview:self.goodsIV];
    [self.bodyView addSubview:self.goodsView];
    [self.bodyView addSubview:self.priceLabel];
    [self.bodyView addSubview:self.salePriceLabel];
    [self.bodyView addSubview:self.lineView];
    [self.bodyView addSubview:self.tableView];
    [self.bodyView addSubview:self.closeBtn];
    [self.bodyView addSubview:self.okBtn];
    [self.bgView addSubview:self.transparentBgView];
    [self.bgView addSubview:self.bodyView];
    [self addSubview:self.bgView];
}


-(UIView *)bgView{
    if(_bgView == NULL){
        _bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight )];
        _bgView.backgroundColor = [UIColor clearColor];
        
    }
    return _bgView;
}

-(UIView *)transparentBgView{
    if(_transparentBgView == NULL){
        _transparentBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _transparentBgView.backgroundColor = [UIColor blackColor];
        _transparentBgView.alpha = 0.6;
    }
    return _transparentBgView;
}

-(UIView *)bodyView{
    if(_bodyView == NULL){
        _bodyView = [[UIView alloc]init];
        _bodyView.backgroundColor = [UIColor whiteColor];
        
    }
    return _bodyView;
}

-(UIView *)goodsView{
    if(_goodsView == NULL){
        _goodsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 102, 102)];
        _goodsView.backgroundColor = [UIColor whiteColor];
        _goodsView.layer.cornerRadius = 5;
        _goodsView.layer.borderWidth = 1;
        _goodsView.layer.borderColor = [kBlack999 CGColor];
        _goodsView.layer.masksToBounds = YES;
        
    }
    return _goodsView;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem *item = self.dataArray[indexPath.row];
    return item.viewHeight;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem* item = self.dataArray[indexPath.row];
    NSString *identifier = NSStringFromClass(item.viewClass);
    ICTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell = [[item.viewClass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if ([item isKindOfClass:[ICTableViewItem class]]) {
        [cell setObject:item];
    }
    
    if ([item isKindOfClass:[EFGoodCountViewItem class]]) {
        ((EFGoodCountViewCell *)cell).changeblock = ^(NSInteger count){
            ((EFGoodCountViewItem*)item).count = count;
        };
    }
    
    if ([item isKindOfClass:[EFGoodScaleViewItem class]]) {
        ((EFGoodScaleViewCell *)cell).selectblock = ^(NSString* title){
            for (NSObject *object in self.dataArray) {
                if([object isKindOfClass:[EFGoodScaleViewItem class]]){
                    EFGoodScaleViewItem* scaleItem = (EFGoodScaleViewItem*)object;
                    for (EFGoodsModelItem *goodsModelItem in  scaleItem.model) {
                        if([goodsModelItem.model_value isEqual:title]){
                            goodsModelItem.select = true;
                        }else{
                            goodsModelItem.select = false;
                        }
                    }
                }
            }

       };
    }
    
    return cell;
}

-(UIImageView *)goodsIV{
    if(_goodsIV == NULL){
        _goodsIV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 76, 83)];
        _goodsIV.left = 15;
        _goodsIV.top = 8;
        _goodsIV.backgroundColor = kGrayColor;
        _goodsIV.contentMode = UIViewContentModeScaleAspectFill;
        _goodsIV.clipsToBounds = YES;
    }
    return _goodsIV;
}


-(UILabel *)priceLabel{
    if(_priceLabel == NULL){
        _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 47, 17)];
        _priceLabel.font = [UIFont systemFontOfSize:17];
        _priceLabel.textColor  = RGBCOLOR(0x69BA45);
        _priceLabel.left = 20;
    }
    return _priceLabel;
}

-(UILabel *)salePriceLabel{
    if(_salePriceLabel == NULL){
        _salePriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 47, 13)];
        _salePriceLabel.font = [UIFont systemFontOfSize:13];
        _salePriceLabel.textColor  = RGBCOLOR(0xCCCCCC);
        _salePriceLabel.left = 20;
    }
    return _salePriceLabel;
}

-(UIView*)lineView{
    if(_lineView == NULL){
        _lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - 40, 1)];
        _lineView.backgroundColor = kBlackDDD;
        
    }
    return _lineView;
}

-(UIButton *)closeBtn{
    if(_closeBtn == NULL){
        _closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        [_closeBtn setImage:IMG(@"nav_btn_close_default")  forState:UIControlStateNormal];
        [_closeBtn addTarget:self action:@selector(onClickClose) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
} 

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kStatusBarHeight - 50 )];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}



-(UIButton *)okBtn{
    if(_okBtn == NULL){
        _okBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        _okBtn.backgroundColor = RGBCOLOR(0x69BA45);
        _okBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        _okBtn.titleLabel.textColor = [UIColor whiteColor];
        [_okBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_okBtn addTarget:self action:@selector(onClickOk) forControlEvents:UIControlEventTouchUpInside];
    }
    return _okBtn;
}




-(void)onClickClose{
    [self removeFromSuperview];
}

-(void)onClickOk{
    if(self.okblock){
        self.okblock(true);
    }
    
    EFGoodCountViewItem* countItem = self.dataArray.lastObject;
    NSMutableString* productId = [[NSMutableString alloc]init];
    EFGoodScaleViewItem* scaleView = nil;
    if([self.dataArray.firstObject isKindOfClass:[EFGoodScaleViewItem class]]){
        EFGoodScaleViewItem* scaleView = self.dataArray.firstObject;
        if(scaleView != nil  && scaleView.model.count >0 ){
            for (EFGoodsModelItem *goodsModelItem in  scaleView.model) {
                if(goodsModelItem.select){
                    productId =  [NSMutableString stringWithFormat:@"%@",goodsModelItem.product_id];
                }
            }
        }else{
            productId = [NSMutableString stringWithFormat:@"%@", self.productId];
        }
    }else{
        productId = [NSMutableString stringWithFormat:@"%@", self.productId];
    }
    
    if(countItem.count <= 0)
        return;
    
    
    if(APP_CONTEXT.accountManager.accountInfo.token.length > 0 ){
        __weak typeof(self) weakSelf = self;
        [APP_CONTEXT.net AddCartId:productId qty:[NSNumber numberWithInteger:countItem.count] type:[NSNumber numberWithInteger:0] OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
            if(self.okblock){
                self.okblock(false);
            }
            if(code == 0){
                 [[iToast makeText:@"成功加入购物车"] show];
                if ([info objectForKey:@"list"]) {
                    NSArray *array = [info objectForKey:@"list"];
                    [APP_CONTEXT.shoppingCartManager.storeProductsCart removeAllObjects];
                    for (NSDictionary *dic in array) {
                        EFSepecialItem *specialItem = [EFSepecialItem yy_modelWithDictionary:dic];
                        if(specialItem.qty == 0 ){
                            specialItem.qty = [NSNumber numberWithInt:1];
                        }
                        
                        [APP_CONTEXT.shoppingCartManager addToStoreProduct:specialItem];
                    }
                }
                
                if(weakSelf.doneblock != NULL){
                    weakSelf.doneblock(countItem.count, scaleView);
                }
                [weakSelf removeFromSuperview];
            }else{
                [[iToast makeText:message]show];
            }
        }];
    }else{
        if(self.okblock){
            self.okblock(false);
        }
        EFSepecialItem *specialItem = [[EFSepecialItem alloc ]init];
        specialItem.id = productId;
        specialItem.qty = [NSNumber numberWithInteger:countItem.count];
        specialItem.price = self.salePrice;
        specialItem.salePrice = self.price;
        
        [APP_CONTEXT.shoppingCartManager addToStoreProduct:specialItem];
        if(self.doneblock != NULL){
            self.doneblock(countItem.count, scaleView);
        }
        [self removeFromSuperview];
    }
    
}




@end
